package initialition

import (
	"exam-app/api/global"
	"exam-app/api/tools"
	pb "exam-app/user-srv/proto"
	"fmt"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"os"
)

func init() {
	InitZap()
	InitConsul()
}

func InitZap() {

	os.MkdirAll("./log", 0777)
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{
		"./log/log",
	}
	build, _ := config.Build()
	zap.ReplaceGlobals(build)
}
func InitConsul() {
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", "117.27.231.169", 8500)
	client, err := api.NewClient(config)
	if err != nil {
		zap.S().Error(err)
	}
	global.ConsulClient = client

	consul := tools.NewConsul("127.0.0.1", 50000)
	filter, err := consul.ConsulFilter("user-srv")
	if err != nil {
		zap.S().Error(err)
	}
	if len(filter) == 0 {
		zap.S().Info("服务未注册到consul")
		err := consul.ConsulRegister("user-srv", "127.0.0.1", 50000, []string{"user-srv", "v1"})
		if err != nil {
			zap.S().Error("服务注册失败")
		} else {
			zap.S().Info("服务注册成功")
		}
	} else {
		zap.S().Info("服务已经注册到consul")
	}
	newClient, err := grpc.NewClient("127.0.0.1:50000", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		zap.S().Error(err)
	}
	global.UserClient = pb.NewUserClient(newClient)

}
